package com.projectx.action.findPassword;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.login.LoginActivity2;
import com.projectx.action.talk.TalkListActivity;
import com.projectx.entity.User;
import com.projectx.entity.UserData;
import com.projectx.util.ActivityManage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class FindAccount extends AppCompatActivity {
    private int choose;
    private ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManage.addActivity("FindAccount",this);
        setContentView(R.layout.find_account);

        final Button next = findViewById(R.id.FindXAccountNext);
        final EditText assistAccountInput = findViewById(R.id.AssistEditText);
        final TextInputLayout textInputLayout = findViewById(R.id.AssistEditField);
        final TextView textView = findViewById(R.id.FindXAccountText);
        progressBar = findViewById(R.id.FindProgress);
        progressBar.setVisibility(View.INVISIBLE);

        TextPaint textPaint = textView.getPaint();
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setStrokeWidth(2);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String assistAccount = assistAccountInput.getText().toString();
                if (assistAccount.isEmpty()){
                    textInputLayout.setError("姓名不能为空");
                } else {
                    textInputLayout.setErrorEnabled(false);
                    FutureTask<JSONObject> task = new FutureTask<>(new Callable<JSONObject>() {
                        @Override
                        public JSONObject call() throws Exception {
                            JSONObject getMessage = null;
                            try {
                                Socket socket = new Socket("106.15.192.117", 2333);
                                Gson gson = new Gson();
                                User user = new User();
                                user.setFlag(7);
                                user.setRealName(assistAccount);
                                String message = gson.toJson(user);
                                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                                dataOutputStream.writeUTF(message);
                                dataOutputStream.flush();
                                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                                String netStr = dataInputStream.readUTF();
                                try {
                                    getMessage = new JSONObject(netStr);
                                } catch (JSONException e) {
                                    Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                                } finally {
                                    dataInputStream.close();
                                    dataOutputStream.close();
                                    socket.close();
                                }

                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                            return getMessage;
                        }
                    });
                    Thread thread = new Thread(task);
                    thread.start();
                    //解析验证JSON字符串返回数据
                    try {
                        JSONObject message = task.get(5, TimeUnit.SECONDS);
                        int code = message.getInt("code");
                        progressBar.setVisibility(View.INVISIBLE);
                        if (code == -1) {
                            throw new Exception();
                        } else if (code == 0){
                            JSONArray jsonArray = (JSONArray) message.get("data");
                            if (jsonArray.length() == 0){
                                AlertDialog.Builder alert = new AlertDialog.Builder(FindAccount.this);
                                alert.setMessage("账号不存在").setPositiveButton("确定",null).show();
                            } else {
                                final String[] strings = new Gson().fromJson(message.getString("data"), String[].class);
                                AlertDialog.Builder chooseOne = new AlertDialog.Builder(FindAccount.this);
                                chooseOne.setSingleChoiceItems(strings, 0, null)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent(FindAccount.this, LoginActivity2.class);
                                        intent.putExtra("accountName",strings[which + 1]);
                                        startActivity(intent);
                                        ActivityManage.exitActivity("FindAccount");
                                    }
                                }).setNegativeButton("取消",null).setTitle("点按选择一个账户").show();
                            }
                        }
                    } catch (TimeoutException te) {
                        Toast.makeText(FindAccount.this, "时间戳错误", Toast.LENGTH_SHORT).show();
                    } catch (JSONException je) {
                        Toast.makeText(FindAccount.this, "服务器错误", Toast.LENGTH_SHORT).show();
                        je.printStackTrace();
                    } catch (Exception ne){
                        ne.printStackTrace();
                        Toast.makeText(FindAccount.this, "网络请求失败", Toast.LENGTH_SHORT).show();
                    } finally {
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
    }
}
